package com.jiangli.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Component
@Slf4j
public class AESUtil {

    private static String AES_KEY;


    private static String AES_IV;

    @Value("${aes.config.key}")
    public void setAesKey
            (String aesKey) {
        AES_KEY = aesKey;
    }
    @Value("${aes.config.iv}")
    public void setAesIv(String aesIv) {
        AES_IV = aesIv;
    }


    // 加密方法
    public static String encrypt(String plainText) throws Exception {
        try {
            log.info(AES_KEY,AES_IV);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(AES_IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new Exception("加密失败", e);
        }
    }

    // 解密方法
    public static String decrypt(String cipherTextBase64) throws Exception {
        try {
            log.info(AES_KEY,AES_IV);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(AES_IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decodedBytes = Base64.getDecoder().decode(cipherTextBase64);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new Exception("解密失败", e);
        }
    }
}